package com.example.administrator.foldingfanfigure.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;



/**
 * Created by Administrator on 2017/10/13.
 */

public class BrokenLineChartView  extends View{



    //设置画笔
    private Paint paint;

    Context content = getContext();

    /**
         * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
        */
  public  int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
           return (int) (dpValue * scale + 0.5f);
           }





    //左上角X
    private int LEFTUPX = dip2px(25);
    //左上角Y
    private int LEFTUPY = dip2px(25);

    //左下角Y
    private int LEETDOWNY= dip2px(200);
    //右下角X
    private int RIGHTDOWNX = dip2px(300);

    //上下间隔
    private int UPDOWNSPACE = dip2px(25);

    //左右间隔
    private  int LEFTRIGHTSPACE=dip2px(25);

    //把x轴等分成多少分（左右间距）
    private int leftrightlines = (RIGHTDOWNX-LEFTUPX)/LEFTRIGHTSPACE;

    private boolean isOne;
    //x轴的坐标值集合
    private ArrayList<Float> listX = new ArrayList<>();
    //Y轴的坐标集合
    private ArrayList<Float> listY = new ArrayList<>();

    private int count = 1;
     private int number = 1; //最大10

    private boolean isFinish ;

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {

            if (number <50){
                number++;
                //刷新view 重新绘制
                invalidate();
                handler.sendEmptyMessageDelayed(1,80);
            }else if (count < leftrightlines -1){
                number = 1;
                count++;
                invalidate();
                handler.sendEmptyMessageDelayed(1,80);

            }else {
                isFinish = true;
                invalidate();
            }
        }
    };


    public BrokenLineChartView(Context context) {
        this(context,null,0);
    }

    public BrokenLineChartView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BrokenLineChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);



        //长度为多少个区间(初始化坐标值)
        for (int i = 0; i <leftrightlines ; i++) {
            //初始化x轴上面的每个区间的左上角坐标值（是等分来的间距一样）
            float x1 = LEFTUPX +(i+1)*LEFTRIGHTSPACE;
            //初始化y轴坐标，随机数
            float y1 = (float)((Math.random()*350)+50);

            listX.add(x1);
            listY.add(y1);
        }
    }
/*
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int  height = 500;
        int width = 200;

        final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(width,height);
        }else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(width,heightSpecSize);
        }else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize,height);
        }
    }*/

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 获取宽-测量规则的模式和大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        // 获取高-测量规则的模式和大小
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 设置wrap_content的默认宽 / 高值
        // 默认宽/高的设定并无固定依据,根据需要灵活设置
        // 类似TextView,ImageView等针对wrap_content均在onMeasure()对设置默认宽 / 高值有特殊处理,具体读者可以自行查看
        int mWidth = dip2px(350);
        int mHeight = dip2px(250);

        // 当布局参数设置为wrap_content时，设置默认值
        if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT && getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(mWidth, mHeight);
            // 宽 / 高任意一个布局参数为= wrap_content时，都设置默认值
        } else if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(mWidth, heightSize);
        } else if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(widthSize, mHeight);
        }
    }

    //画图
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        getPaint().reset();
        //======================画坐标轴begin==========================
        /*
        * 外框线
        * */
        //设置颜色
        getPaint().setColor(Color.parseColor("#A5A5A5"));
        //设置宽度
        getPaint().setStrokeWidth(2);
        //线的坐标点（四个为一条线）(-20y坐标系加上 20,因为屏幕中Y轴为负值)
        float[] pts = {LEFTUPX,LEFTUPY-20,LEFTUPX,LEETDOWNY,LEFTUPX,LEETDOWNY,RIGHTDOWNX+20,LEETDOWNY};
        //画线(坐标，画笔)
        canvas.drawLines(pts,getPaint());

        //======================画坐标轴end==========================


        //======================画箭头begin==========================
        //通过路径画三角形
        Path path  = new Path();
        getPaint().setStyle(Paint.Style.FILL);//设置为空心
        path.moveTo(LEFTUPX-5,LEFTUPY-20); //此点为多边形的起点
        path.lineTo(LEFTUPX+5,LEFTUPY-20); //多边形的右下角
        path.lineTo(LEFTUPX,LEFTUPY-35);   //多边形的顶角
        path.close(); //使这些点构成封闭的多边形
        canvas.drawPath(path,getPaint());

        //第二个箭头
        path.moveTo(RIGHTDOWNX+20,LEETDOWNY-5);
        path.lineTo(RIGHTDOWNX+20,LEETDOWNY+5);
        path.lineTo(RIGHTDOWNX+35,LEETDOWNY);
        canvas.drawPath(path,getPaint());

        //======================画箭头end==========================


        //======================中间虚线begin==========================
        int updownlines = (LEETDOWNY-LEFTUPY)/UPDOWNSPACE;//y轴位置等分

        float[] pts2 = new float[(updownlines+leftrightlines)*4]; //记录每一个区域的  4个坐标点


        //======================Y轴上数字begin==========================
        //计算位置
        for (int i = 0; i < updownlines; i++) {
            float x1 = LEFTUPX;     //从0 开始起
            float y1 = LEETDOWNY -(i+1) * UPDOWNSPACE;
            float x2 = RIGHTDOWNX;
            float y2 = LEETDOWNY -(i+1)*UPDOWNSPACE;

            //把坐标值添加到数组中 1-23
            pts2[i*4+0] =x1;
            pts2[i*4+1] =y1;
            pts2[i*4+2] =x2;
            pts2[i*4+3] =y2;

            getPaint().setColor(Color.BLACK);
            getPaint().setTextSize(25);
            canvas.drawText(String.valueOf(i),x1-25,y1+10,getPaint());

        }
        //======================Y轴上数字end==========================

        //计算位置
        for (int i = 0; i <leftrightlines ; i++) {
            float x1 = LEFTUPX+(i+1)*LEFTRIGHTSPACE;
            float y1 = LEFTUPY;
            float x2 =  LEFTUPX+(i+1)*LEFTRIGHTSPACE;
            float y2 = LEETDOWNY;
    //24-最后
            pts2[(i+ updownlines)*4+0]=x1;
            pts2[(i+ updownlines)*4+1]=y1;
            pts2[(i+ updownlines)*4+2]=x2;
            pts2[(i+ updownlines)*4+3]=y2;

            getPaint().setColor(Color.BLACK);
            getPaint().setTextSize(25);
            canvas.drawText(String.valueOf(i),x2-10, y2+30,getPaint());
        }

        getPaint().setColor(Color.parseColor("#E0E0E0"));
        getPaint().setStrokeWidth(1);
        int length = pts2.length;
        canvas.drawLines(pts2,getPaint());


        //======================中间虚线end==========================


        if (isOne){
            //线的路径
            Path path2 = new Path();
            //共几个转折点
            for (int i = 0; i <count; i++) {
                if (i==0){
                    path2.moveTo(listX.get(i),listY.get(i));
                }else {
                    path2.lineTo(listX.get(i),listY.get(i));
                }


            }
        /*  //  path.close(); //使这些点构成封闭的多边形
            getPaint().setStyle(Paint.Style.FILL);//设置为空心
            getPaint().setColor(Color.BLACK);
            canvas.drawPath(path2,getPaint());*/

        //上一个点，减去下一个点的位置，计算中间点位置
            path2.lineTo(listX.get(count-1)+(listX.get(count)-listX.get(count-1))/50*number,
                    listY.get(count-1) +(listY.get(count)-listY.get(count-1))/50*number);
            getPaint().setColor(Color.parseColor("#FF7A00"));
            getPaint().setStrokeWidth(3);
            getPaint().setStyle(Paint.Style.STROKE); //设置为空心
            canvas.drawPath(path2,getPaint());
            path2.lineTo(listX.get(count-1) +(listX.get(count) - listX.get(count-1))/50*number,LEETDOWNY);
            path2.lineTo(listX.get(0),LEETDOWNY);
            path2.lineTo(listX.get(0),listY.get(0));
            getPaint().setStyle(Paint.Style.FILL); //设置为实心

            canvas.drawPath(path2,getShadeColorPaint());
            getPaint().reset();
            //画出转折点圆心
            for (int i = 0; i <count ; i++) {
                //画外圆
                getPaint().setColor(Color.parseColor("#FF7A00"));

                getPaint().setStyle(Paint.Style.FILL);
                canvas.drawCircle(listX.get(i) ,listY.get(i),7,getPaint());
                //画中心点为白色
                getPaint().setColor(Color.WHITE);
                getPaint().setStyle(Paint.Style.FILL);
                canvas.drawCircle(listX.get(i),listY.get(i),4,getPaint());
            }
            handler.sendEmptyMessage(1);
        }
    }



    public void drawBrokenLine(){
        isOne = true;
        number =1;
        count =1;
        isFinish =false;
        invalidate();
    }

    //获取画笔
    private Paint getPaint(){
        if (paint ==null){
            paint = new Paint();
        }
        return paint;
    }

    //修改笔的颜色
    private Paint getShadeColorPaint(){
        Shader mShader  = new LinearGradient(300,50,300,400,
                new int[]{Color.parseColor("#55FF7A00"), Color.TRANSPARENT},null,Shader.TileMode.CLAMP);
        /*新建一个线性渐变，前两个参数是渐变开始的点坐标，第三四个参数是渐变结束的点的坐标，连接着这两个点
        就拉出一条渐变线了，玩过ps的都懂。然后那个数组是渐变的颜色，下一个参数是渐变颜色的分布，如果为空，每个
        颜色就是均匀分布的，最后是模式，这里设置的是循环渐变*/
        getPaint().setShader(mShader);
        return  getPaint();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Toast.makeText(getContext(),"==========" + event.getX() + "===" + event.getY(),Toast.LENGTH_SHORT).show();;
        return super.onTouchEvent(event);
    }
}
